<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2022/4/7
 * Time: 6:32 下午
 */

namespace app\api\controller\v31;

use app\api\controller\v2\Auth;
use app\common\cachemodel\Article;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\ArticleCommentGood;
use app\common\cachemodel\ArticleCommentReply;
use app\common\cachemodel\GoddessArea;
use app\common\cachemodel\GoddessBaseInfo;
use app\common\cachemodel\zl1_relation\Zl1AstrCommunityArticle;
use app\common\cachemodel\zl2\Zl2AstrFortuneArticle;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\ZlGoddessState;
use app\common\lib\ConfigManage;
use app\common\lib\Util;
use app\common\model\MessageCenter;
use app\common\model\User;
use think\Cache;
use XznsTools\cache\CacheManage;

/**
 * Class QuestionMessage
 * @package app\api\controller\v31
 */
class QuestionMessage extends Auth
{
    /**
     * 问答消息中心
     * @return array|\think\response\Json
     * @throws \Exception
     */
    public function index()
    {
        $type = input('type/d', 0);
        switch ($type)
        {
            case 3: //点赞
                $data = $this->getGood();
                break;
            case 4://评论回复
                $data = $this->getReply();
                break;
            default:
                return show(config('code.error'), '未知的消息');
        }
        $data['num_list'] = (new MessageCenter())->getUnreadMsgNum($this->user['id']);
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 获取回复列表
     */
    protected function getReply()
    {
        $filterType = input('filter_type/d', 0);//0=>全部, 1=>问答, 2=>视频, 3=>话题, 4=>星文, 5=>星座讨论
        if ($filterType === 1)
        {
            $filterType = 4;
        } elseif ($filterType === 4)
        {
            $filterType = 1;
        }
        $replyModel = new ArticleCommentReply();
        $page = input('page/d', 1);
        $ids = $replyModel->getUserReplyMeFromCache($this->user['id'], $filterType);
        $num = count($ids);
        $data_list = getPaginatorData($num, $page);
        //获取分页后的数据
        $ids = array_slice($ids, $data_list['start'], 10);
        unset($data_list['start'], $data_list['end']);
        $data = $replyModel->batchGetInfoByIds($ids, ['id', 'create_time', 'content', 'duration', 'pid', 'comment_id', 'good_num', 'uid1', 'uid2', 'content_type', 'type', 'aid', 'content2', 'is_goddess', 'status']);
        $data_list['data'] = $this->replyMeDataFormat($ids, $data);
        return $data_list;
    }

    /**
     * 回复我的数据重组
     * @param array $ids 回复的id
     * @param array $commentReplyDatas 回复的数据
     * @return array
     * @throws \app\common\lib\exception\ApiException
     */
    protected function replyMeDataFormat(array $ids, array $commentReplyDatas)
    {
        $userIds = [];
        $articleModel = new Article();
        $goddessStateModel = new ZlGoddessState();
        $goddessAreaModel = new GoddessArea();
        $articleCommentReplyModel = new ArticleCommentReply();
        $goddessInfoModel = new GoddessBaseInfo();
        foreach ($commentReplyDatas as $commentReplyDataItem)
        {
            $userIds[] = $commentReplyDataItem['uid1'];
            $userIds[] = $commentReplyDataItem['uid2'];
        }
        $userIds = array_unique(array_filter($userIds));
        // 批量获取用户信息
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['avatar', 'nickname']);
        // 获取回复阅读情况
        $read_ids = $articleCommentReplyModel->getUserReadReply($this->user['id']);
        $unread_ids = array_diff($ids, $read_ids);
        //获取内部官方用户
        $configModel = new ConfigManage();
        $questionModel = new Zlcr2UserQuestion();
        $commentModel = new ArticleComment();
        $astrCommunityArticleModel = new Zl1AstrCommunityArticle();
        $astrFortuneArticleModel = new Zl2AstrFortuneArticle();
        $resData = [];
        $identity = 0;
        $isAnonymity = false;
        foreach ($ids as $id)
        {
            $target = 'local';
            $commentType = '回复了';
            $link = '';
            $tipTitle = '';
            //获取文章信息
            switch ($commentReplyDatas[$id]['type'])
            {
                case 1://星文
                    $article = current($articleModel->batchGetInfo([$commentReplyDatas[$id]['aid']], ['id', 'title']));
                    $tipTitle = $article['title'];
                    $link = "article_info?id={$commentReplyDatas[$id]['aid']}&type=1&content_type=1&need_auth=0";
                    break;
                case 2://动态
                    $article = $goddessStateModel->getInfoById($commentReplyDatas[$id]['aid'], ['id', 'type', 'title']);
                    $tipTitle = $article['title'];
                    $link = "article_info?id={$commentReplyDatas[$id]['aid']}&type=2&content_type={$article['type']}&need_auth=0";
                    break;
                case 3://话题
                    $article = current($goddessAreaModel->batchGetThemeInfo([$commentReplyDatas[$id]['aid']], ['id', 'title']));
                    $tipTitle = $article['title'];
                    $link = "article_info?id={$commentReplyDatas[$id]['aid']}&type=3&content_type=1&need_auth=0";
                    break;
                case 4://问答
                    $comment = current($commentModel->batchGetInfo([$commentReplyDatas[$id]['comment_id']], ['uid', 'status']));
                    $link = "question_detail?qid={$commentReplyDatas[$id]['aid']}&comment_id={$commentReplyDatas[$id]['comment_id']}&need_auth=0";

                    if ($commentReplyDatas[$id]['pid'])
                    {
                        $tipTitle = '我的评论';
                        $commentType = '回复了';
                    } else
                    {

                        $tipTitle = '我的讨论';
                        $commentType = '评论了';
                    }

                    if (isset($comment['status']) && $comment['status'] < 0)
                    {
                        $target = 'toast';
                        $link = '该讨论已删除';
                    }
                    $article = $questionModel->getInfoById($commentReplyDatas[$id]['aid'], ['uid', 'is_anonymity', 'delete_time']);
                    if ($article['delete_time'] > 0)
                    {
                        $target = 'toast';
                        $link = '该问答已删除';
                    }
                    //获取用户身份标识,  楼主,提问者,未读状态
                    if ((int)$commentReplyDatas[$id]['uid1'] === (int)$comment['uid'])
                    {
                        $identity = 2;//楼主
                    }
                    if ((int)$commentReplyDatas[$id]['uid1'] === (int)$article['uid'])
                    {
                        $identity = 1;//提问者
                        if ($article['is_anonymity'] === 1)
                        {
                            $isAnonymity = true;
                        }
                    }
                    break;
                case 5:
                    $article = $astrCommunityArticleModel->getInfoById($commentReplyDatas[$id]['aid'], ['id', 'title']);
                    $tipTitle = $article['title'];
                    $link = "sign_discuss_detail?id={$commentReplyDatas[$id]['aid']}&is_change_tab=0&need_auth=0";
                    break;
                case 6:
                    $article = $astrFortuneArticleModel->getInfoById($commentReplyDatas[$id]['aid'], ['id', 'title']);
                    $tipTitle = $article['title'];
                    $link = "astro_foutune_change_article_detail?id={$commentReplyDatas[$id]['aid']}&need_auth=2";
            }
            $goddessInfo = [];
            if ($commentReplyDatas[$id]['is_goddess'])
            {
                $goddessInfo = $goddessInfoModel->getInfo(['nickname', 'avatar']);
                if ($goddessInfo)
                {
                    if ($commentReplyDatas[$id]['content_type'] == 2)//回复类型为音频
                    {
                        $commentReplyDatas[$id]['content'] = '一条语音回复';
                    }
                }
            }

            $nickname = $goddessInfo['nickname'] ?? ($userInfoList[$commentReplyDatas[$id]['uid1']]['nickname'] ?? '匿名用户');
            $avatar = $goddessInfo['avatar'] ?? ($userInfoList[$commentReplyDatas[$id]['uid1']]['avatar'] ?? '');

            $resData[] = [
                'id' => (int)$id,
                'nickname' => $isAnonymity && $identity === 1 ? '匿名用户' : $nickname,
                'avatar' => $isAnonymity && $identity === 1 ? '/test/question_answer/anonymity1.png' : $avatar,
                'identity' => $identity,
                'user_type' => $configModel->innerUser((int)($commentReplyDatas[$id]['uid1'] ?? 0)), //获取内部官方用户
                'create_time' => Util::timeToStr($commentReplyDatas[$id]['create_time']),
                'content' => $commentReplyDatas[$id]['content'],//回复内容
                'type' => (int)$commentReplyDatas[$id]['type'],
                'tip_title' => mb_strlen($tipTitle) > 7 ? mb_substr($tipTitle, 0, 7) . '...' : $tipTitle,//我的评论/我的讨论/5月桃花TOP榜（文章标题/话题）
                'tip_content' => $commentReplyDatas[$id]['content2'],//评论数据
                'comment_type' => $commentType,//回复了/评论了/讨论了/对你的评论表示同感/对你的讨论表示同感/同问了你的问题
                'target' => $target,
                'link' => $link,
                'is_read' => $unread_ids ? in_array($id, $unread_ids, false) ? 0 : 1 : 1,
            ];
        }
        return $resData;
    }

    /**
     * 获取点赞列表
     */
    protected function getGood()
    {
        //删除未读点赞缓存
        Cache::rm('user_good_unread_status_' . $this->user['id']);

        $page = input('page/d', 1);
        $goodModel = new ArticleCommentGood();
        $ids = $goodModel->getGoodIds($this->user['id'], 0, 0, 2);
        $num = count($ids);
        $data_list = getPaginatorData($num, $page);
        //获取分页后的数据
        $ids = array_slice($ids, $data_list['start'], 10);
        unset($data_list['start'], $data_list['end']);
        $data = $goodModel->batchGetInfoByIds($ids);
        $userIds = array_unique(array_column($data, 'uid'));
        // 批量获取用户信息
        $userInfoList = (new User())->batchGetUserInfo($userIds, ['avatar', 'nickname']);
        //获取内部官方用户
        $configModel = new ConfigManage();
        $stateModel = new ZlGoddessState();
        $questionModel = new Zlcr2UserQuestion();
        $commentModel = new ArticleComment();
        $resData = [];
        $delCache = false;
        foreach ($ids as $id)
        {
            if (!isset($data[$id]))
            {
                if (!$delCache)
                {
                    CacheManage::getInstance()->setCacheConfig('content.comment_good', $this->user['id'] . '-' . 4 . '-' . 0)->setListKeyType(2)->rmCache('list');
                    $delCache = true;
                }
                continue;
            }
            //获取用户身份标识,  楼主,提问者,未读状态
            $identity = 0;
            //获取评论回复信息
            if ((int)$data[$id]['type'] === 1)
            {
                $commentReplyDatas = current($commentModel->batchGetInfo([$data[$id]['comment_id']], ['content', 'uid', 'status']));
                $commentIsDel = $commentReplyDatas['status'] < 0 ? true : false;
                $titleType = $data[$id]['article_type'] == 4 ? '讨论' : '评论';
                $tipTitle = '我的' . $titleType;
                $commentType = "对你的{$titleType}表示同感";
                if ((int)$data[$id]['uid'] === (int)$commentReplyDatas['uid'])
                {
                    $identity = 2;//楼主
                }
                $commentId = $data[$id]['comment_id'];
            } else
            {
                $commentReplyDatas = (new ArticleCommentReply())->getInfoById($data[$id]['comment_id'], ['content', 'comment_id']);
                $comment = current($commentModel->batchGetInfo([$commentReplyDatas['comment_id']], ['status']));
                $commentIsDel = $comment['status'] < 0 ? true : false;
                $titleType = $data[$id]['article_type'] == 4 ? '评论' : '回复';
                $tipTitle = "我的{$titleType}";
                $commentType = "对你的{$titleType}表示同感";
                $commentId = $commentReplyDatas['comment_id'];
            }
            $nickname = $userInfoList[$data[$id]['uid']]['nickname'] ?? '匿名用户';
            $avatar = $userInfoList[$data[$id]['uid']]['avatar'] ?? '';
            $link = '';
            switch ($data[$id]['article_type'])
            {
                case 1://星文
                    $link = "article_info?id={$data[$id]['aid']}&type={$data[$id]['article_type']}&content_type=0&need_auth=0";
                    break;
                case 2://动态
                    $info = $stateModel->getInfoById($data[$id]['aid']);
                    $link = "article_info?id={$data[$id]['aid']}&type={$data[$id]['article_type']}&content_type={$info['type']}&need_auth=0";
                    break;
                case 3://话题
                    $link = "article_info?id={$data[$id]['aid']}&type={$data[$id]['article_type']}&content_type=0&need_auth=0";
                    break;
                case 4:
                    $question = $questionModel->getInfoById($data[$id]['aid'], ['uid', 'is_anonymity', 'delete_time']);
                    if ((int)$data[$id]['uid'] === (int)$question['uid'])
                    {
                        $identity = 1;//提问者
                        if ($question['is_anonymity'] === 1)
                        {
                            $nickname = '匿名用户';
                            $avatar = '/test/question_answer/anonymity1.png';
                        }
                    }
                    $link = "question_detail?qid={$data[$id]['aid']}&comment_id={$commentId}&need_auth=0";
                    if ($question['delete_time'] > 0)
                    {   // 已删除问题情况
                        $commentIsDel = true;
                    }
                    break;
                case 5:
                    $link = "sign_discuss_detail?is_change_tab=1&id={$data[$id]['aid']}&need_auth=0";
                    break;
                case 6:
                    $link = "astro_foutune_change_article_detail?id={$data[$id]['aid']}&need_auth=2";
                    break;
            }


            $resData[] = [
                'id' => (int)$id,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'identity' => $identity,
                'user_type' => $configModel->innerUser((int)($data[$id]['uid'] ?? 0)), //获取内部官方用户
                'create_time' => Util::timeToStr($data[$id]['create_time']),
                'content' => '',//回复内容
                'type' => (int)$data[$id]['article_type'],
                'tip_title' => $tipTitle ?? '',//我的评论/我的讨论/5月桃花TOP榜（文章标题/话题）
                'tip_content' => $commentReplyDatas['content'],//评论数据
                'comment_type' => $commentType,//回复了/评论了/讨论了/对你的评论表示同感/对你的讨论表示同感/同问了你的问题
                'target' => $commentIsDel ? 'toast' : 'local',
                'link' => $commentIsDel ? '该讨论已删除' : $link,
                'is_read' => 1
            ];
        }
        $data_list['data'] = $resData;
        return $data_list;
    }
}
